
//  HomeOrderTechnician.m
//  XJMTechnician
//  Created by Mr.hu on 2017/10/16.
//  Copyright © 2017年 Mr.hu. All rights reserved.

#import "HomeOrderTechnician.h"
#import "OrderTechnicianCell.h"
#import "NewsRemindVC.h"
#import "CurrentOrder_Arrive.h"
#import <CoreLocation/CoreLocation.h>
#import "LoginMainVC.h"

#import "EarnMoney_VC.h"
#import <SIOSocket/SIOSocket.h>
#import "lawIntroduceView.h"

//#import "XJMTechnician-Swift.h"

@interface HomeOrderTechnician ()<UITableViewDelegate,UITableViewDataSource,CLLocationManagerDelegate>

/** 注释 **/
@property (strong, nonatomic) CLLocationManager * locationManager;

@property (weak, nonatomic) IBOutlet UIButton *NewsRedRemind;
@property (weak, nonatomic) IBOutlet UIButton *ComminteOrder;
@property (weak, nonatomic) IBOutlet UILabel *TotallistNumber;

@property (weak, nonatomic) IBOutlet UITableView *OrderTableView;

@property (weak, nonatomic) IBOutlet UILabel *Congratulation_address;
@property (weak, nonatomic) IBOutlet UILabel *Congratulation_telephone;
@property (weak, nonatomic) IBOutlet UILabel *Congratulation_message;

@property (weak, nonatomic) IBOutlet UIButton *Congratulation_Comment;
@property (weak, nonatomic) IBOutlet UIView *Congratulation_PopView;
@property (strong, nonatomic) NSDictionary * PlaceDict;
@property (nonatomic,strong)  NSMutableArray * arrlist;
@property (nonatomic) NSInteger page;

@property SIOSocket *socket;
@property BOOL socketIsConnected;

/** 注释 **/
@property (strong, nonatomic) UIView * remindnews;
@property (nonatomic)  NSTimer *timer_Socket;
@property NSMutableDictionary *pins;
@property (nonatomic,strong) NSDictionary * ReceiveOrder_dict; //收到订单消息数组
@property (weak, nonatomic) IBOutlet UILabel *Order_ComplitetyFirst;
@property (weak, nonatomic) IBOutlet UILabel *Order_ComplitetySecond;
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate_secret;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *top_HeightView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *Top_SubHeightView;
@property (nonatomic,copy) NSString * Order_status;
/** 注释 **/
@property (strong, nonatomic) lawIntroduceView * lawIntroduce;

@end

@implementation HomeOrderTechnician

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.tabBarItem.title = @"订单";
        self.navigationItem.title = @"订单";
        self.tabBarItem.image = [[UIImage imageNamed:@"dingdanDefault"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        self.tabBarItem.selectedImage = [[UIImage imageNamed:@"dingdan"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    }
    return self;
}



- (void)lawSureIntroducceOnclicked{
    
    [self.lawIntroduce removeFromSuperview];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.arrlist = [NSMutableArray array];
    
    self.ComminteOrder.layer.cornerRadius = 15;
    self.ComminteOrder.layer.masksToBounds = YES;
    self.Congratulation_PopView.hidden = YES;
    
    //无订单出现
    self.OrderTableView.hidden = YES;
    self.Congratulation_PopView.hidden = YES;
    self.TotallistNumber.hidden = YES;
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(jkr_tapGestureAction:)];
    tapGestureRecognizer.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGestureRecognizer];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    NSInteger value = [[[NSUserDefaults standardUserDefaults] objectForKey:ktabbarChangeValue] integerValue];
    if (value) {
        [self.navigationController setNavigationBarHidden:NO animated:YES];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    //第一次进入首页的时候有新手指导
    //    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"lawIntroduce"] == NO) {
    //        [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"lawIntroduce"];
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        AFHTTPSessionManager * sessionmanager = [[AFHTTPSessionManager alloc]init];
        //申明返回来的结果是二进制类型
        sessionmanager.responseSerializer = [AFHTTPResponseSerializer serializer];
        //如果报接受类型不一致，请替换一致text/html  或者 text/plain
        sessionmanager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
        //设置请求超时时间
        [sessionmanager.requestSerializer setTimeoutInterval:30.0];
        
        [sessionmanager GET:@"http://api.xijiaomo.com/tech.php/v2/Notice/techer_mianze" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSString * friendstg =[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSData * frienddata =[friendstg dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary * frienddict = [NSJSONSerialization JSONObjectWithData:frienddata options:NSJSONReadingMutableContainers error:nil];
            NSDictionary * datadict =frienddict[@"data"];
            
            self.lawIntroduce = [[lawIntroduceView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
            self.lawIntroduce.backgroundColor = RGBA(95, 94, 86, 0.8);
            if (datadict[@"title"]) {
                self.lawIntroduce.titlelawlab.text = datadict[@"title"];
            }
            if (datadict[@"content"]) {
                self.lawIntroduce.DetailablLab.text = [NSString stringWithFormat:@"%@\n\n\n\n\n\n\n\n\n\n\n\n\n",datadict[@"content"]];
            }
            [[UIApplication sharedApplication].keyWindow addSubview:self.lawIntroduce];
            [self.lawIntroduce.LawSureBtn addTarget:self action:@selector(lawSureIntroducceOnclicked) forControlEvents:UIControlEventTouchUpInside];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
    });
    //    }
    
    if ([XJToolClass getUserId]) {
        [self CheckTechDonotComplitely]; //检测技师未完成订单
    }else{
        self.OrderTableView.hidden = YES; //隐藏
        self.Congratulation_PopView.hidden = YES;
    }
}

- (void)jkr_tapGestureAction:(UITapGestureRecognizer *)tapGusture{
    
    self.remindnews.hidden = YES;
}

- (void)CheckTechDonotComplitely{
    
    [XJHttpClass TeachComplityOrderRemindToken:[XJToolClass getToken] andFinishblock:^(id response, NSString *errStr) {
        
        if (errStr) {
            [XJToolClass tipAnimationWith:errStr];
            //            [self requestServerData]; //无未完成订单
            
        }else{
            
            //判断有无未完成的订单
            NSString * statuecomplite = response[@"message"];
            if ([statuecomplite isEqualToString:@"无未完成订单"]) {
                NSDictionary * accountdict = response[@"data"];
                self.Order_status = accountdict[@"status"];
                
            }else{
                
                //status=1审核通过，status=0未审核，status=3女性技师早八点晚八点不能接单
                self.ReceiveOrder_dict = response[@"data"];
                self.Order_status = self.ReceiveOrder_dict[@"status"];
                if ([self.Order_status isEqualToString:@"0"]) {
                    [XJToolClass tipAnimationWith:@"账号审核中"];
                }else if ([self.Order_status isEqualToString:@"1"]){
                    
                    self.Congratulation_PopView.hidden = NO;
                    self.remindnews = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
                    self.remindnews.backgroundColor = RGBA(95, 94, 86, 0.8);
                    self.Congratulation_PopView.layer.cornerRadius = 30;
                    self.Congratulation_PopView.layer.masksToBounds = YES;
                    [self.remindnews addSubview:self.Congratulation_PopView];
                    [self.Congratulation_PopView mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.centerY.mas_equalTo(0);
                        make.size.mas_equalTo(CGSizeMake(ScreenWidth-80, 350));
                        make.left.mas_equalTo(40);
                    }];
                    [[UIApplication sharedApplication].keyWindow addSubview:self.remindnews];
                    
                    NSDictionary * orderdict = response[@"data"];
                    self.Congratulation_address.text = orderdict[@"address"];
                    self.Order_ComplitetyFirst.text = @"您还有未完成的订单";
                    self.Order_ComplitetyFirst.font = [UIFont systemFontOfSize:16];
                    self.Order_ComplitetySecond.text =  @"";
                    if (orderdict[@"mobile"]) {
                        self.Congratulation_telephone.text = [NSString stringWithFormat:@"联系电话:%@",orderdict[@"mobile"]];
                    }else{
                        self.Congratulation_telephone.text = [NSString stringWithFormat:@"联系电话:"];
                    }
                    
                    if (orderdict[@"user_note"]) {
                        NSString * usernote = [NSString stringWithFormat:@"留言 : %@",orderdict[@"user_note"]];
                        if (usernote) {
                            self.Congratulation_message.text = usernote;
                        }
                    }else{
                        NSString * usernote = [NSString stringWithFormat:@"留言 : "];
                        if (usernote) {
                            self.Congratulation_message.text = usernote;
                        }
                    }
                    
                    [self.Congratulation_Comment addTarget:self action:@selector(NextPopViewMeth) forControlEvents:UIControlEventTouchUpInside];
                    self.Congratulation_Comment.layer.cornerRadius = 22;
                    self.Congratulation_Comment.layer.masksToBounds = YES;
                    
                }else if ([self.Order_status isEqualToString:@"3"]){
                    
                    [XJToolClass tipAnimationWith:@"女性技师早八点晚八点不能接单哦"];
                    
                }
            }
        }
    }];
    
}

- (void)requestServerData{
    
    _locationManager = [[CLLocationManager alloc] init];
    
    if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways)) {
        
        //定位功能可用
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
            [_locationManager requestWhenInUseAuthorization];
        }
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        CLLocationDistance distance = 10.0;
        _locationManager.distanceFilter = distance;
        [_locationManager startUpdatingLocation];
        
    }else if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
        [XJToolClass showLocationOpenTip:self];
    }
}

- (void)tableviewKneadappoint{
    
    self.OrderTableView.delegate = self;
    self.OrderTableView.dataSource = self;
    self.OrderTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.OrderTableView registerNib:[UINib nibWithNibName:@"OrderTechnicianCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"OrderTechnicianCell"];
    self.page=1;
    self.OrderTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self refreshRequestLoading:1];
        [self.OrderTableView.mj_header endRefreshing];
    }];
    
    self.OrderTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self refreshRequest:++self.page];
        //        [self.OrderTableView.mj_footer endRefreshing];
    }];
    self.OrderTableView.mj_footer.automaticallyHidden = YES;
    [self refreshRequestLoading:1];
    
}

-(void)refreshRequestLoading:(NSInteger)page{
    
    if ([self.PlaceDict isKindOfClass:[NSDictionary class]]) {
        
        if ([XJToolClass getToken]) {
            
            [XJHttpClass teachReceiveOrderListToken:[XJToolClass getToken] t_lat:self.PlaceDict[@"tatiduteplace"] t_lon:self.PlaceDict[@"longtitudeplace"] page:[NSString stringWithFormat:@"%ld",page]  andFinishblock:^(id response, NSString *errStr) {
                
                if (errStr) {
                    //隐藏后出现无订单显示
                    if ([errStr isEqualToString:@""]) {
                        
                    }
                    self.OrderTableView.hidden = YES;
                    self.Congratulation_PopView.hidden = YES;
                    
                }else{
                    NSDictionary * datadict = response[@"data"];
                    if ([datadict isKindOfClass:[NSDictionary class]]) {
                        NSArray * arrcount = datadict[@"list"];
                        if (arrcount.count > 0) {
                            
                            [self.arrlist removeAllObjects];
                            self.arrlist = datadict[@"list"];
                            self.TotallistNumber.text = [NSString stringWithFormat:@"共收到%@条订单",datadict[@"count"]];
                        }
                    }
                    
                    self.OrderTableView.hidden = NO;
                    
                    [self.OrderTableView reloadData];
                    
                }
            }];
        }
    }
}

-(void)refreshRequest:(NSInteger)page{
    
    if ([self.PlaceDict isKindOfClass:[NSDictionary class]]) {
        [XJHttpClass teachReceiveOrderListToken:[XJToolClass getToken] t_lat:self.PlaceDict[@"tatiduteplace"] t_lon:self.PlaceDict[@"longtitudeplace"] page:[NSString stringWithFormat:@"%ld",page]  andFinishblock:^(id response, NSString *errStr) {
            
            if (errStr) {
                //隐藏后出现无订单显示
                //            self.OrderTableView.hidden = YES;
                //            self.Congratulation_PopView.hidden = YES;
                [self.OrderTableView.mj_footer endRefreshingWithNoMoreData];
                
            }else{
                NSDictionary * datadict = response[@"data"];
                if ([datadict isKindOfClass:[NSDictionary class]]) {
                    NSArray * arrcount = datadict[@"list"];
                    if (arrcount.count > 0) {
                        
                        [self.arrlist addObject:datadict[@"list"]];
                        self.TotallistNumber.text = [NSString stringWithFormat:@"共收到%@条订单",datadict[@"count"]];
                    }else{
                        [self.OrderTableView.mj_footer endRefreshingWithNoMoreData];
                    }
                }
                
                self.OrderTableView.hidden = NO;
                [self.OrderTableView reloadData];
                
            }
        }];
    }else{
        [self.OrderTableView.mj_footer endRefreshing];
        [self.OrderTableView.mj_footer endRefreshingWithNoMoreData];
    }
}

#pragma mark - TableViewDatasource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrlist.count > 0 ? self.arrlist.count : 0;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderTechnicianCell * friend=[tableView dequeueReusableCellWithIdentifier:@"OrderTechnicianCell"];
    if(friend==nil){
        friend=[[OrderTechnicianCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"OrderTechnicianCell"];
    }
    
    friend.Order_CirclePrice.layer.borderColor = RGBA(222, 37, 35, 1).CGColor;
    friend.Order_CirclePrice.layer.borderWidth = 0.8;
    friend.Order_CirclePrice.layer.cornerRadius = 8;
    
    friend.backview_OrderCircle.layer.cornerRadius = 10;
    [friend setdata:self.arrlist[indexPath.row]];
    friend.Order_RobBtn.tag = indexPath.row;
    [friend.Order_RobBtn addTarget:self action:@selector(RobOrderListMeth:) forControlEvents:UIControlEventTouchUpInside];
    
    friend.selectionStyle = UITableViewCellSelectionStyleNone;
    friend.userInteractionEnabled = YES;
    
    return friend;
}

- (void)RobOrderListMeth:(UIButton *)sender{
    [XJToolClass tipAnimationWith:@"恭喜您加入抢单队列"];
}

- (void)NextPopViewMeth{
    
    self.remindnews.hidden = YES;
    
    CurrentOrder_Arrive * currentarrive = [[CurrentOrder_Arrive alloc]init];
    currentarrive.Customer_latitude = self.ReceiveOrder_dict[@"u_lat"];
    currentarrive.Customer_longtitude = self.ReceiveOrder_dict[@"u_lon"];
    currentarrive.CustomerOrder_Dict = self.ReceiveOrder_dict;
    currentarrive.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:currentarrive animated:YES];
}

#pragma mark TableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 135;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //当手指离开某行时，就让某行的选中状态消失
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (IBAction)NewsRemindMeth:(id)sender {
    
    if ([XJToolClass getUserId]) {
        NewsRemindVC * newsRemind = [[NewsRemindVC alloc]init];
        newsRemind.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:newsRemind animated:YES];
    }else{
        LoginMainVC * newsRemind = [[LoginMainVC alloc]init];
        newsRemind.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:newsRemind animated:YES];
    }
}

- (IBAction)EarnMoneyMeth:(id)sender {
    if ([XJToolClass getUserId]) {
        EarnMoney_VC * newsRemind = [[EarnMoney_VC alloc]init];
        newsRemind.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:newsRemind animated:YES];
    }else{
        LoginMainVC * newsRemind = [[LoginMainVC alloc]init];
        newsRemind.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:newsRemind animated:YES];
    }
}

#pragma mark --开始接单
- (IBAction)ComminteOrderMeth:(UIButton *)sender {
    
    //先判断登录状态
    if ([XJToolClass getUserId]) {
        if ([self.Order_status isEqualToString:@"0"] || !self.Order_status) {
            [XJToolClass tipAnimationWith:@"账号审核中"];
        }else if ([self.Order_status isEqualToString:@"1"]){  //可以接单
            
            //判断是否审核通过 检查技师接单状态
            [XJHttpClass CheckTechStatusToken:[XJToolClass getToken] andFinishblock:^(id response, NSString *errStr) {
                
                if (errStr) {
                    [XJToolClass tipAnimationWith:@"账号审核中"];
                }else{
                    if (sender.selected == NO) {
                        self.TotallistNumber.hidden = NO;
                        
                        if ([XJToolClass getToken]) {
                            
                            [self tableviewKneadappoint];
                            
                            [XJHttpClass teachReceiveOrderListToken:[XJToolClass getToken] t_lat:[NSString stringWithFormat:@"%f",_coordinate_secret.latitude] t_lon:[NSString stringWithFormat:@"%f",_coordinate_secret.longitude] page:@"1"  andFinishblock:^(id response, NSString *errStr) {
                                
                                if (errStr) {
                                    //隐藏后出现无订单显示
                                    self.OrderTableView.hidden = YES; //隐藏
                                    self.Congratulation_PopView.hidden = YES;
                                    
                                }else{
                                    NSDictionary * datadict = response[@"data"];
                                    if ([datadict isKindOfClass:[NSDictionary class]]) {
                                        self.arrlist = datadict[@"list"];
                                        self.TotallistNumber.text = [NSString stringWithFormat:@"共收到%@条订单",datadict[@"count"]];
                                        self.OrderTableView.hidden = NO; //隐藏
                                        [self.OrderTableView reloadData];
                                    }else{
                                        self.OrderTableView.hidden = YES; //隐藏
                                        self.Congratulation_PopView.hidden = YES;
                                    }
                                }
                            }];
                            
                        }else{
                            self.OrderTableView.hidden = YES; //隐藏
                            self.Congratulation_PopView.hidden = YES;
                        }
                        
                        [self startOrderSocketConnect];
                        [sender setTitle:@"停止接单" forState:UIControlStateNormal];
                        
                        sender.selected = YES;
                        
                    }else {
                        
                        self.TotallistNumber.hidden = YES;
                        self.OrderTableView.hidden = YES; //无订单显示
                        self.Congratulation_PopView.hidden = YES;
                        
                        NSString * MDStr =  [XJToolClass sha1:[XJToolClass md5:[NSString stringWithFormat:@"signature=%@&tid=%@",PrivatyKeySecret,[XJToolClass getUserId]]]];
                        NSString * PinJie = [NSString stringWithFormat:@"signature=%@&tid=%@",MDStr,[XJToolClass getUserId]];
                        [self.socket emit: @"close" args: @[PinJie]];
                        //停止socket连接
                        [self.socket on:@"close" callback:^(SIOParameterArray *args) {
                            
                        }];
                        [self.timer_Socket invalidate];
                        
                        [sender setTitle:@"开始接单" forState:UIControlStateNormal];
                        sender.selected = NO;
                    }
                    
                }
            }];
            
        }else if ([self.Order_status isEqualToString:@"3"]){
            [XJToolClass tipAnimationWith:@"女性技师早八点晚八点不能接单哦"];
        }
        
    }else{
        
        LoginMainVC * login = [[LoginMainVC alloc]init];
        login.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:login animated:YES];
        
    }
}

- (void)startOrderSocketConnect{
    
    [SIOSocket socketWithHost:SocketIDHost reconnectAutomatically:YES attemptLimit:10 withDelay:1 maximumDelay:5 timeout:20 response:^(SIOSocket *socket) {
        self.socket = socket;
        
        NSString * MDStr =  [XJToolClass sha1:[XJToolClass md5:[NSString stringWithFormat:@"signature=%@&tid=%@",PrivatyKeySecret,[XJToolClass getUserId]]]];
        NSString * PinJie = [NSString stringWithFormat:@"signature=%@&tid=%@",MDStr,[XJToolClass getUserId]];
        
        //定位
        NSString * locationstr =  [NSString stringWithFormat:@"tid=%@&&lat=%f&lon=%f",[XJToolClass getUserId],_coordinate_secret.latitude,_coordinate_secret.longitude];
        
        __weak typeof(self) weakSelf = self;
        self.socket.onConnect = ^{
            
            [weakSelf.socket emit: @"login" args: @[PinJie]];
            [weakSelf.socket on:@"login" callback:^(SIOParameterArray *args) {
                
            }];
            //定位
            [weakSelf.socket emit: @"locations" args: @[locationstr]];
            [weakSelf.socket on:@"locations" callback:^(SIOParameterArray *args) {
                
            }];
            
            weakSelf.timer_Socket = [NSTimer scheduledTimerWithTimeInterval:15.0 target:weakSelf selector:@selector(ConnectSocketMeth) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer: weakSelf.timer_Socket forMode:NSDefaultRunLoopMode];
            
            //客户端接收消息
            NSString * pushmesg = [NSString stringWithFormat:@"push_msg%@",[XJToolClass getUserId]];
            [weakSelf.socket on:pushmesg callback:^(SIOParameterArray *args) {
                
                id obj = args.firstObject;
                NSData *jsonData = [obj dataUsingEncoding:NSUTF8StringEncoding];
                NSError *err;
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                    options:NSJSONReadingMutableContainers
                                                                      error:&err];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    weakSelf.Congratulation_PopView.hidden = NO;
                    weakSelf.remindnews = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
                    weakSelf.remindnews.backgroundColor = RGBA(95, 94, 86, 0.8);
                    weakSelf.Congratulation_PopView.layer.cornerRadius = 30;
                    weakSelf.Congratulation_PopView.layer.masksToBounds = YES;
                    [weakSelf.remindnews addSubview:weakSelf.Congratulation_PopView];
                    [weakSelf.Congratulation_PopView mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.centerY.mas_equalTo(0);
                        make.size.mas_equalTo(CGSizeMake(ScreenWidth-80, 350));
                        make.left.mas_equalTo(40);
                    }];
                    [[UIApplication sharedApplication].keyWindow addSubview:weakSelf.remindnews];
                    
                    weakSelf.ReceiveOrder_dict = dic[@"data"];
                    weakSelf.Order_ComplitetyFirst.text = @"恭喜您";
                    weakSelf.Order_ComplitetyFirst.font = [UIFont systemFontOfSize:30];
                    weakSelf.Order_ComplitetySecond.text =  @"抢单成功";
                    weakSelf.Congratulation_address.text = weakSelf.ReceiveOrder_dict[@"address"];
                    weakSelf.Congratulation_telephone.text = [NSString stringWithFormat:@"联系电话:%@",weakSelf.ReceiveOrder_dict[@"mobile"]];
                    NSString * usernote = [NSString stringWithFormat:@"留言 : %@",weakSelf.ReceiveOrder_dict[@"user_note"]];
                    if (usernote) {
                        weakSelf.Congratulation_message.text = usernote;
                    }
                    
                    [weakSelf.Congratulation_Comment addTarget:weakSelf action:@selector(NextPopViewMeth) forControlEvents:UIControlEventTouchUpInside];
                    weakSelf.Congratulation_Comment.layer.cornerRadius = 22;
                    weakSelf.Congratulation_Comment.layer.masksToBounds = YES;
                });
            }];
        };
    }];
}

- (void)ConnectSocketMeth{
    
    NSString * MDStr =  [XJToolClass sha1:[XJToolClass md5:[NSString stringWithFormat:@"signature=%@&tid=%@",PrivatyKeySecret,[XJToolClass getUserId]]]];
    NSString * PinJie = [NSString stringWithFormat:@"signature=%@&tid=%@",MDStr,[XJToolClass getUserId]];
    
    __weak typeof(self) weakSelf = self;
    [SIOSocket socketWithHost:SocketIDHost reconnectAutomatically:YES attemptLimit:10 withDelay:1 maximumDelay:5 timeout:20 response:^(SIOSocket *socket) {
        
        self.socket = socket;
        [weakSelf.socket emit: @"pingpong" args: @[PinJie]];
        [weakSelf.socket on:@"pingpong" callback:^(SIOParameterArray *args) {
            
            id obj = args.firstObject;
            NSData *jsonData = [obj dataUsingEncoding:NSUTF8StringEncoding];
            NSError *err;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                options:NSJSONReadingMutableContainers
                                                                  error:&err];
            
        }];
    }];
}

#pragma mark 跟踪定位代理方法，每次位置发生变化即会执行（只要定位到相应位置）
//可以通过模拟器设置一个虚拟位置，否则在模拟器中无法调用此方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation *location=[locations firstObject];//取出第一个位置
    _coordinate_secret = location.coordinate;//位置坐标
    [_locationManager stopUpdatingLocation];
    //    NSString *positionString = [NSString stringWithFormat:@"%f,%f",coord.latitude,coord.longitude];
    //    [self getNearStation:positionString];
    
    CLLocation *transLocation = [[CLLocation alloc]initWithLatitude:_coordinate_secret.latitude longitude:_coordinate_secret.longitude];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:transLocation
                   completionHandler:^(NSArray *placemarks, NSError *error){
                       if (error) {
                       }
                       if (placemarks.count>0) {
                           CLPlacemark *place = [placemarks objectAtIndex:0];
                           NSString *city = place.locality;
                           NSString *area = place.subLocality;
                           if (!city) {
                               //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                               city = place.administrativeArea;
                           }
                           
                           self.PlaceDict = @{@"longtitudeplace":[NSString stringWithFormat:@"%f",_coordinate_secret.longitude],@"tatiduteplace":[NSString stringWithFormat:@"%f",_coordinate_secret.latitude],@"addressplace":city};
                           [self startOrderSocketConnect];
                       }
                   }];
    
}

// 错误信息
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    //    [self getNearStation:nil];
}

@end
